package com.des1gn.ymgetil.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;

@Slf4j
public class AesUtil {

    private static final String iv = "1234567890000000";

    public static String decoderAes(String content,String sessionId,String key){
        if(content.length() < 32){
            return null;
        }
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());
        String result = null;
        try {
            result = new String(aes.decrypt(content), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("AES解密错误,{}",e);
        }
        return result;
    }

    public static String getKey(String sessionId){
        JWT jwt = JWTUtil.parseToken(sessionId);
        String val = jwt.getPayload("val").toString().replaceAll("\r\n","");
        String decoderVal = Base64.decodeStr(val,"UTF-8");
        decoderVal = decoderVal.substring(decoderVal.indexOf("\u0010") + 1,decoderVal.indexOf("\u001C"));
        String key = decoderVal.substring(0,16);
        return key;
    }

}
